package leetcode;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class ValidParentheses {

    public static void main(String[] args) {
        ValidParentheses v = new ValidParentheses();
        System.out.println(v.isValid("(])"));
    }

    public boolean isValid(String s) {
            if(s.length() % 2 > 0) return false;
        Deque<Character> deque = new LinkedList<>();
        Map<Character, Character> pairs = new HashMap<Character, Character>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if(pairs.containsKey(ch)){
                if (deque.isEmpty() || deque.peek() != pairs.get(ch)) {
                    return false;
                }
                deque.pop();
            }else{
                deque.push(ch);
            }
        }
        return deque.isEmpty();
    }



}
